package examples.complex.viewmodel.personlogin

import de.saxsys.mvvmfx.ViewModel
import de.saxsys.mvvmfx.utils.commands.Action
import de.saxsys.mvvmfx.utils.commands.Command
import de.saxsys.mvvmfx.utils.commands.DelegateCommand
import de.saxsys.mvvmfx.utils.itemlist.ModelToStringFunction
import de.saxsys.mvvmfx.utils.itemlist.SelectableItemList
import de.saxsys.mvvmfx.utils.itemlist.SelectableStringList
import examples.complex.model.Person
import examples.complex.model.Repository
import javafx.application.Platform
import javafx.beans.binding.BooleanBinding
import javafx.beans.property.ReadOnlyObjectProperty
import javafx.beans.property.ReadOnlyObjectWrapper
import javafx.collections.FXCollections

import javax.inject.Inject

/**
 * Created by Misty on 2015/6/5.
 */
class PersonLoginViewModel implements ViewModel {
    private ReadOnlyObjectWrapper<Integer> loggedInPersonId = new ReadOnlyObjectWrapper<>()
    private SelectableItemList<Person> selectablePersons
    Command loginCommand

    final Repository repository

    @Inject
    public PersonLoginViewModel(Repository repository) {
        this.repository = repository
        this.loginCommand = new DelegateCommand({ -> [action: { performLogin() }] as Action },
                createLoginPossibleBinding(), true)
    }

    private BooleanBinding createLoginPossibleBinding() {
        return selectablePersonsProperty().selectedIndexProperty().isNotEqualTo(-1)
    }

    SelectableStringList selectablePersonsProperty() {
        if (selectablePersons == null) {
            def f = { Person person -> return "${person.firstName} ${person.lastName}" } as ModelToStringFunction
            selectablePersons = new SelectableItemList<Person>(
                    FXCollections.<Person> observableArrayList(repository.persons), f)
        }
        return selectablePersons
    }

    ReadOnlyObjectProperty<Integer> loggedInPersonIdProperty() {
        return loggedInPersonId.getReadOnlyProperty()
    }

    private void performLogin() {
        try {
            Thread.sleep(500)
        } catch (Exception ignore) {
        }

        Platform.runLater {
            loggedInPersonId.set(selectablePersons.getSelectedItem().id)
            loggedInPersonId.set(null)
        }
        publish(PersonLoginViewModelNotifications.OK.id, PersonLoginViewModelNotifications.OK.message)
    }
}
